import type { RouteRecordRaw } from 'vue-router'

export let firstMenu: any = null
export default function activeRoutes(userMenus: any[]) {
  // 1.动态获取所有路由对象，放入数组中
  const localRoutes: RouteRecordRaw[] = []
  // 读取router/main中所有.ts文件
  const files: Record<string, any> = import.meta.glob(
    '../router/main/**/*.ts',
    {
      eager: true
    }
  )
  // 遍历所有文件，将路由对象添加到数组中
  for (const file in files) {
    const module = files[file]
    localRoutes.push(module.default)
  }
  // 2.根据用户的菜单，动态添加路由
  const routes: RouteRecordRaw[] = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      const route = localRoutes.find((item) => item.path === submenu.url)
      if (route) {
        routes.push(route)
      }
      if (!firstMenu && route) firstMenu = submenu
    }
  }
  return routes
}

// 记录当前路由所对应菜单的id
export function mapPathToMenu(path: string, userMenus: any[]) {
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        return submenu
      }
    }
  }
  return undefined
}

// 路由和面包屑的映射
export function mapPathToBreadcrumb(path: string, userMenus: any[]) {
  const breadcrumb: any[] = []
  for (const menu of userMenus) {
    for (const submenu of menu.children) {
      if (submenu.url === path) {
        breadcrumb.push({ name: menu.name, path: submenu.url })
        breadcrumb.push({ name: submenu.name, path: submenu.url })
      }
    }
  }
  return breadcrumb
}
